<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="group_name" prop="groupName" label-width="100px">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入group_name"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="user_name" prop="userName" label-width="100px">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入user_name"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="group_id" align="center" prop="groupId" />
      <el-table-column label="user_id" align="center" prop="userId" />
      <el-table-column label="group_name" align="center" prop="groupName" />
      <el-table-column label="user_name" align="center" prop="userName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分组用户关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="分组名称" prop="groupId">
              <el-select
                v-model="form.groupId"
                placeholder="请选择分组"            style="width: 100%"
                @change="handleGroupChange">
                <el-option
                  v-for="group in groupOptions"
                  :key="group.groupId"
                  :label="group.groupName"
                  :value="group.groupId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户名称" prop="userId">
              <el-select
                v-model="form.userId"
                filterable
                remote
                reserve-keyword
                placeholder="请选择用户"
                :remote-method="searchUsers"
                :loading="userLoading"            style="width: 100%"
                @change="handleUserChange">
                <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId">
                </el-option>
              </el-select>
            </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/purchase/user"
import { listGroup } from "@/api/purchase/group"
import { listUser as listAllUsers } from "@/api/system/user" // 系统用户API

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分组用户关联表格数据
      userList: [],
      // 分组选项
      groupOptions: [],
      // 用户选项
      userOptions: [],
      // 用户加载状态
      userLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        userName: null
      },
      // 表单参数
      form: {
        groupId: null,
        userId: null,
        groupName: null,
        userName: null
      },
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: "请选择分组", trigger: "change" }
        ],
        userId: [
          { required: true, message: "请选择用户", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询分组用户关联列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        groupId: null,
        userId: null,
        groupName: null,
        userName: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.groupId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加分组用户关联"
      // 获取分组和用户选项
      this.getGroupOptions()
      this.getUserOptions()
    },
    /** 获取分组选项 */
    getGroupOptions() {
      listGroup().then(response => {
        this.groupOptions = response.rows
      })
    },
    /** 获取用户选项 */
    getUserOptions() {
      this.userLoading = true
      listAllUsers().then(response => {
        this.userOptions = response.rows || response.data || []
        this.userLoading = false
      }).catch(() => {
        this.userLoading = false
      })
    },
    /** 搜索用户 */
    searchUsers(query) {
      if (query !== '') {
        this.userLoading = true
        listAllUsers({ userName: query }).then(response => {
          this.userOptions = response.rows || response.data || []
          this.userLoading = false
        }).catch(() => {
          this.userLoading = false
        })
      } else {
        this.getUserOptions()
      }
    },
    /** 分组选择变化 */
    handleGroupChange(groupId) {
      // 根据选择的分组ID找到对应的分组名称
      const selectedGroup = this.groupOptions.find(group => group.groupId === groupId)
      if (selectedGroup) {
        this.form.groupName = selectedGroup.groupName
      }
      console.log("选择的分组:", selectedGroup)
    },
    /** 用户选择变化 */
    handleUserChange(userId) {
      // 根据选择的用户ID找到对应的用户名称
      const selectedUser = this.userOptions.find(user => user.userId === userId)
      if (selectedUser) {
        this.form.userName = selectedUser.userName
      }
      console.log("选择的用户:", selectedUser)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const groupId = row.groupId || this.ids
      getUser(groupId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改分组用户关联"
        // 获取分组和用户选项
        this.getGroupOptions()
        this.getUserOptions()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保分组名称和用户名称已设置
          if (this.form.groupId && !this.form.groupName) {
            const selectedGroup = this.groupOptions.find(group => group.groupId === this.form.groupId)
            if (selectedGroup) {
              this.form.groupName = selectedGroup.groupName
            }
          }

          if (this.form.userId && !this.form.userName) {
            const selectedUser = this.userOptions.find(user => user.userId === this.form.userId)
            if (selectedUser) {
              this.form.userName = selectedUser.userName
            }
          }

          // 构造数据对象（包含ID和名称）
          const data = {
            groupId: this.form.groupId,
            userId: this.form.userId,
            groupName: this.form.groupName,
            userName: this.form.userName
          }

          console.log("提交的数据:", data) // 调试用

          // 检查是否已存在该关联
          const existing = this.userList.find(item =>
            item.groupId === this.form.groupId && item.userId === this.form.userId)

          if (this.form.groupId && existing && this.title !== "修改分组用户关联") {
            this.$modal.msgWarning("该分组用户关联已存在")
            return
          }

          if (this.title === "修改分组用户关联") {
            updateUser(data).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError("修改失败: " + (response.msg || "未知错误"))
              }
            }).catch(error => {
              this.$modal.msgError("修改失败: " + (error.message || "网络错误"))
            })
          } else {
            addUser(data).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError("新增失败: " + (response.msg || "未知错误"))
              }
            }).catch(error => {
              this.$modal.msgError("新增失败: " + (error.message || "网络错误"))
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const groupIds = row.groupId || this.ids
      this.$modal.confirm('是否确认删除分组用户关联编号为"' + groupIds + '"的数据项？').then(function() {
        return delUser(groupIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>


